<?php

namespace App\Models\Issue;

class IssueService
{
    protected $repository;

    public function __construct(IssueRepository $repository)
    {
        $this->repository = $repository;
    }

    public function createAndGetId(array $data)
    {
        $data = array_merge([
            'type' => Issue::TYPE_QUIZ,
            'description' => '',
            'configuration' => [],
        ], $data);

        $issue = new Issue();
        $issue->fill($data);
        $saved = $this->repository->store($issue);

        return $saved->id;
    }

    public function update($id, $data)
    {
        $issue = $this->repository->getOneById($id);

        if (is_null($issue)) {
            abort(404);
        }

        return $issue->fill($data)->save();
    }

    public function delete($id)
    {
        $issue = $this->repository->getOneById($id);

        if (is_null($issue)) {
            abort(404);
        }

        return $issue->delete();
    }

    public function has($id)
    {
        return null !== $this->repository->getOneById($id);
    }
}
